//
//  LocalDataHandle.m
//  XiangMuB
//
//  Created by lanou3g on 16/8/21.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "LocalDataHandle.h"

#import <CoreData/CoreData.h>
#import "PersonMessage.h"

@interface LocalDataHandle ()

@property (strong, nonatomic) NSManagedObjectContext *content;

@end

static LocalDataHandle *handle = nil;

@implementation LocalDataHandle


+ (instancetype)shareDataHandle{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        handle = [[LocalDataHandle alloc] init];
    });
    
    return handle;
}

- (void)createManagedContentObject{
    
    self.content = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    
    NSURL *modelUrl = [[NSBundle mainBundle] URLForResource:@"PersonModel" withExtension:@"momd"];
    
    NSManagedObjectModel *objectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelUrl];
    
    NSPersistentStoreCoordinator *storeCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:objectModel];
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    path = [path stringByAppendingPathComponent:@"personMessage.sqlite"];
    
    [storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:path] options:nil error:nil];
    
    
    self.content.persistentStoreCoordinator = storeCoordinator;
    
}


- (void)saveDataWithCellContentModleToLocal:(CellContentModel *)model{
    
    [self createManagedContentObject];
    
    PersonMessage *personModel = [NSEntityDescription insertNewObjectForEntityForName:@"PersonMessage" inManagedObjectContext:self.content];
    personModel.personData = [CellContentModel archiveWithCellContentModel:model];
    
    [self.content save:nil];
    
    
}

- (NSArray *)getDataWithCellContentModleFromLocal{
    
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"PersonMessage" inManagedObjectContext:self.content];
    
    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    [fetch setEntity:entity];
    
    NSError *error = nil;
    NSArray *array = [self.content executeFetchRequest:fetch error:&error];
    
    if (array.count == 0) {
        NSLog(@"获取数据失败");
        return nil;
    } else {
        NSLog(@"获取数据成功");
    }
    
    return array;
    
}



@end
